package com.haiyuancloud.auth.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haiyuancloud.auth.service.ValidateCodeService;
import com.haiyuancloud.common.core.entity.CurrentUser;
import com.haiyuancloud.common.core.exception.ValidateCodeException;
import com.haiyuancloud.common.redis.service.CommonRedisService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author haiyuan
 */
@Controller
@Slf4j
@RequiredArgsConstructor
public class SecurityController {

    private final ValidateCodeService validateCodeService;

    @Resource
    private CommonRedisService commonRedisService;

    @ResponseBody
    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        log.info("use info:"+principal.getName());
        return principal;
    }

    @SneakyThrows
    @ResponseBody
    @PostMapping("currentUserInfo")
    public CurrentUser currentUserInfo() {
        OAuth2Authentication authentication =  (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        LinkedHashMap<String, Object> authenticationDetails = (LinkedHashMap<String, Object>) authentication.getUserAuthentication().getDetails();
        Object principal = authenticationDetails.get("principal");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(mapper.writeValueAsString(principal), CurrentUser.class);
    }


    @ResponseBody
    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
        validateCodeService.create(request, response);
    }

    @ResponseBody
    @GetMapping("listPrd")
    public Map<String,Object> listPrd(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
        Map<String,Object> listPrd = new HashMap<>();
        String key = "L_TB_UI_PRODUCT";
        List<Map<String,Object>> productList = (List<Map<String,Object>>)commonRedisService.get(key);
        listPrd.put("data",productList);
        return listPrd;
    }

    @RequestMapping("login")
    public String login() {
        return "login";
    }
}
